package com.swak.boot.config.jdbc.mapper.async;

import java.util.List;
import java.util.Set;

import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.util.StringUtils;

import com.swak.async.persistence.mapper.Mapper;
import com.swak.boot.Application;
import com.swak.utils.Lists;

/**
 * 自动注解查找的类
 * 
 * @author lifeng
 * @date 2020年4月13日 下午9:51:51
 */
public class AsyncMapperScannerRegistrar implements ImportBeanDefinitionRegistrar {

	/**
	 * {@inheritDoc}
	 */
	@Override
	public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
		List<String> packages = this.resolveMapperModelPackages();
		BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(AsyncMapperScannerConfigurer.class);
		builder.addPropertyValue("annotationClass", Mapper.class);
		builder.addPropertyValue("basePackage", StringUtils.collectionToCommaDelimitedString(packages));
		registry.registerBeanDefinition(AsyncMapperScannerConfigurer.class.getName(), builder.getBeanDefinition());
	}

	/**
	 * 获取 Mappers -- Mapper 类
	 * 
	 * @return
	 */
	public List<String> resolveMapperModelPackages() {
		List<String> _mapperLocations = Lists.newArrayList();
		Set<String> mapperLocations = Application.getScanPackages();
		for (String mapperLocation : mapperLocations) {
			if (!com.swak.utils.StringUtils.endsWith(mapperLocation, ".mapper")) {
				_mapperLocations.add(String.format("%s.**.mapper", mapperLocation));
			}
		}
		return _mapperLocations;
	}
}